import { _decorator, Animation, CCFloat, Component, instantiate, Node, sp, Vec3 } from 'cc';
import { PathUtil } from '../utils/PathUtil';
import { EffectManager } from '../game/EffectManager';
import { Enemy } from '../actor/Enemy';
import { EnemyManger } from '../actor/EnemyManger';
import { Projectile } from './Projectile';
import { StateDefine } from '../actor/StateDefine';
import { Constants } from '../game/Constants';
import { GameDefine } from '../game/GameDefine';
import { AudioManager } from '../game/AudioManager';
import { Louis } from './Louis';
import { CameraManager } from '../game/CameraManager';
const { ccclass, property } = _decorator;

@ccclass('FortressBase')
export class FortressBase extends Component {
    public isActived: boolean = false; // 要塞是否激活

    @property(sp.Skeleton) anim: sp.Skeleton = null!; // 要塞动画

    /** 手动攻击 */
    @property(Node) playerFirePoint: Node = null!;
    @property(Node) projectileNode: Node = null!;
    @property({ type: Node, displayName: "攻击范围" })
    dropPoint: Node = null!;

    /** 自动攻击 */
    @property(Node) autoFirePoint: Node = null!;
    @property(Node) projectileBall: Node = null!;
    @property(Animation) autoFireAnim: Animation = null!;
    autoFireState: StateDefine = StateDefine.idle;

    /** 发射间隔（秒） */
    @property({ tooltip: '发射间隔（秒）' })
    shootInterval: number = 1;
    private _lastFireTime: number = 0;

    // 要塞NPC1: 发射子弹
    @property(Louis) louis: Louis = null!;

    // 闪电攻击特效
    @property(Node)
    lightEffect: Node = null!;
    lightInterval: number = 2;

    @property(Node)
    fireEffect: Node = null!;
    fireInterval: number = 2;

    private atkTarget: Enemy = null; // 当前攻击目标

    start() {
        this.louis.targetPoint = this.dropPoint.getWorldPosition();
        this.node.on(Constants.Event_FortressAtk, this.onFortressAtk, this);
    }

    update(deltaTime: number) {
        if (!this.isActived) return;

        if (GameDefine.isGamePaused) {
            this.anim.paused = true; // 暂停动画
            return;
        } else {
            this.anim.paused = false; // 恢复动画
        }

        // 检测是否有敌人进入攻击范围
        if (this.checkEnemyInRange()) {
            this.louis.tryAttack(this.atkTarget.node);
            this.changeAutoFireState(StateDefine.atk);
            this.playLightEffect();
            this.playFireEffect();
        } else {
            this.louis.tryAttack(null);
            this.changeAutoFireState(StateDefine.idle);
        }
    }

    /** 检测是否有敌人进入攻击范围 */
    private checkEnemyInRange(): boolean {
        // TODO: 实现敌人检测逻辑
        if (this.atkTarget && !this.atkTarget.isDead) {
            return true;
        }
        this.atkTarget = EnemyManger.Instance.getEnemyInRange(this.dropPoint.getWorldPosition());
        return this.atkTarget != null;
    }

    /**
     * 播放要塞开火动画
     */
    public changeAutoFireState(newState: StateDefine) {
        if (this.autoFireState === newState)
            return;
        this.autoFireState = newState;

        const animName = StateDefine[newState];
        const animState = this.autoFireAnim.getState(animName);
        // 检查动画是否存在
        if (animState == null) {
            console.warn(`动画不存在: ${animName}`);
            return;
        }
        animState.wrapMode = 2; // 1:播放一次 2:循环播放
        if (newState === StateDefine.atk) {
            this.autoFireAnim.crossFade("atk", 0.1);
        } else {
            this.autoFireAnim.crossFade("idle", 0.1);
        }
    }

    /** 要塞攻击 */
    private onFortressAtk() {
        if (!this.atkTarget || this.atkTarget.isDead) {
            console.log("没有有效的攻击目标");
            return;
        }
        const projectileNode = instantiate(this.projectileBall);
        if (!projectileNode) {
            console.error("投射物预制体不存在");
            return;
        }
        AudioManager.Instance.playFortressCast();
        const beginPos = this.autoFirePoint.getWorldPosition();
        projectileNode.setParent(this.node);
        projectileNode.setWorldPosition(beginPos);
        projectileNode.setRotation(this.autoFirePoint.getRotation());
        projectileNode.active = true;

        const ProjectileComp = projectileNode.getComponent(Projectile);
        if (ProjectileComp) {
            ProjectileComp.setAttackTarget(0.2, this.atkTarget);
            this.scheduleOnce(() => {
                this.atkTarget?.killEnemy();
            }, 0.2)
        }
    }

    /**
     * 播放发射动画（带冷却与落点随机）
     */
    public onPlayFireAnim() {
        const now = Date.now() * 0.001;
        if (now - this._lastFireTime < this.shootInterval) return; // 冷却中
        this._lastFireTime = now;
        // 创建 3 个投掷物，间隔 0.1s
        const count = 3;
        const interval = 0.1;
        const baseBeginPos = this.playerFirePoint.getWorldPosition();
        const baseEndPos = this.dropPoint.getWorldPosition();
        for (let i = 0; i < count; i++) {
            this.scheduleOnce(() => {
                const projectileNode = instantiate(this.projectileNode);
                if (!projectileNode) {
                    console.error('投射物预制体不存在');
                    return;
                }
                projectileNode.setParent(this.node);

                // 每个投掷物的起点使用当前固定起点
                const beginPos = baseBeginPos.clone();
                // 给每个落点增加少量横向偏移，i 越大偏移越大
                const endPos = baseEndPos.clone();
                endPos.x += -50 * i;

                projectileNode.setWorldPosition(beginPos);
                projectileNode.active = true;

                PathUtil.setupDropAnimation(projectileNode, beginPos, endPos, 1, 200, () => {
                    projectileNode.destroy();
                    EnemyManger.Instance.doAreaDamage(5);
                    AudioManager.Instance.playCommonExplosion();
                    EffectManager.Instance.playExplodeEffect(endPos);
                });
            }, interval * i);
        }
    }

    private _lastLightTime: number = 0;
    private playLightEffect() {
        // 要塞等级不足,武器未解锁
        if (GameDefine.FortressLevel <= 1)
            return;
        // 发射时间间隔
        const now = Date.now() * 0.001;
        if (now - this._lastLightTime < this.lightInterval) {
            return;
        }

        EnemyManger.Instance.doAreaDamage(5);
        CameraManager.Instance.shakeCamera();
        this._lastLightTime = now;
        const lightNode = instantiate(this.lightEffect);
        if (lightNode) {
            lightNode.active = true;
            lightNode.setParent(this.node);
            lightNode.setPosition(0, 0, 0);
        }
    }

    private _lastFireEffectTime: number = 0;
    private playFireEffect() {
        // 要塞等级不足,武器未解锁
        if (GameDefine.FortressLevel < 4)
            return;

        // 冷却检测
        const now = Date.now() * 0.001;
        if (now - this._lastFireEffectTime < this.fireInterval) return;
        this._lastFireEffectTime = now;

        EnemyManger.Instance.doAreaDamage(10);
        CameraManager.Instance.shakeCamera();
        // 生成火焰特效
        const fireNode = instantiate(this.fireEffect);
        if (fireNode) {
            fireNode.active = true;
            fireNode.setParent(this.node);
            fireNode.setPosition(0, 0, 0);
        }
    }
}


